package com.yuyou.fn.platform.service.impl;

import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.common.constant.Constants;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.platform.service.IAreaTeamService;
import com.yuyou.fn.platform.service.IBusTeamService;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.CriteriaUtils;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.platform.vo.SysUserQueryVo;
import com.yuyou.fn.platform.vo.SysUserSaveOrUpdateVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import com.yuyou.fn.platform.mapper.SysUserMapper;
import com.yuyou.fn.platform.entity.SysUser;
import com.yuyou.fn.platform.service.ISysUserService;
import com.github.wens.framework.service.impl.SuperServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.regex.Pattern;

/**
 *
 * SysUser 表数据服务层接口实现类
 *
 */
@Service
public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser,Long> implements ISysUserService {

    private static final Pattern MOBILE_PATTERN = Pattern.compile("1\\d{10}");

    @Resource
    private IAreaTeamService areaTeamService ;

    @Resource
    private IBusTeamService busTeamService ;

    @Override
    public SysUser login(String username, String passwordMd5Hash) {
        Example<SysUser> userExample = SysUser.createExample();
        Example.Criteria criteria = userExample.createCriteria();
        criteria.andEqualTo("password", passwordMd5Hash);
        if (MOBILE_PATTERN.matcher(username).matches()) {
            criteria.andEqualTo("phoneNo", username);
        } else {
            criteria.andEqualTo("username", username);
        }
        return  findOneByExample(userExample);
    }

    @Override
    public Page<SysUser> findSysUserByQueryForPage(SysUserQueryVo sysUserQueryVo, int pageNo, int pageSize) {

        Example<SysUser> example = SysUser.createExample();
        example.orderBy("createTime").desc() ;
        Example.Criteria criteria = example.createCriteria();
        CriteriaUtils.fillCondition(criteria,sysUserQueryVo);

        return findPageByExample(example,pageNo , pageSize );
    }



    @Override
    public void saveOrUpdateSysUser(SysUserSaveOrUpdateVo sysUserSaveOrUpdateVo) {
        SysUser sysUser = new SysUser();

        sysUserSaveOrUpdateVo.setPassword(null);
        BeanUtils.copyProperties(sysUser,sysUserSaveOrUpdateVo);
        fillExtraData(sysUser) ;

        if(sysUser.getUserId() == null ){
            sysUser.setStatus(1);
            sysUser.setPassword(DigestUtils.md5Hex("yuyou123"));
            sysUser.setCreateTime(TimeUtils.now());
            sysUser.setUpdateTime(TimeUtils.now());
            checkSysUser(sysUser);
            insertSelective(sysUser);
        }else{
            checkSysUser(sysUser);
            sysUser.setUpdateTime(TimeUtils.now());
            updateSelectiveById(sysUser);
        }
    }

    private void checkSysUser(SysUser sysUser) {
        Example<SysUser> example = SysUser.createExample();
        example.createCriteria().andEqualTo("username",sysUser.getUsername() );
        SysUser one = findOneByExample(example);

        if(one!= null && (one.getUserId() == null || !one.getUserId().equals(sysUser.getUserId())) ){
            throw new BusException("用户名重复");
        }


    }

    private void fillExtraData(SysUser sysUser) {
        if(sysUser.getUserType() == Constants.USER_TYPE_OF_YUYOU ){
            sysUser.setBusTeamId(0l);
            sysUser.setBusTeamName("");
            sysUser.setAreaTeamId(0l);
            sysUser.setAreaTeamName("");
        }else if(sysUser.getUserType() == Constants.USER_TYPE_OF_AREA ){
            sysUser.setAreaTeamName(areaTeamService.findTeamNameById(sysUser.getAreaTeamId()));
            sysUser.setBusTeamId(0l);
            sysUser.setBusTeamName("");
        }else if(sysUser.getUserType() == Constants.USER_TYPE_OF_BUS ){
            sysUser.setAreaTeamName(areaTeamService.findTeamNameById(sysUser.getAreaTeamId()));
            sysUser.setBusTeamName(busTeamService.findTeamNameById(sysUser.getBusTeamId()));
        }
    }

    @Override
    public void updateSysUserStatus(Long userId, Integer status) {

        if(status != 0 && status != 1 ){
            throw new IllegalArgumentException("invalid status");
        }

        SysUser sysUser = new SysUser() ;
        sysUser.setUserId(userId);
        sysUser.setStatus(status);
        updateSelectiveById(sysUser);

    }

    @Override
    @Transactional
    public void changePassword(Long userId, String oldPassword, String newPassword) {
        SysUser sysUser = findById(userId);
        if(!sysUser.getPassword().equals(oldPassword)){
            throw new BusException("原密码不正确");
        }
        SysUser update = new SysUser();
        update.setUserId(userId);
        update.setPassword(newPassword);
        updateSelectiveById(update);
    }

    @Override
    public void deleteUser(Long userId) {
        deleteById(userId);
    }
}